package com.example.blue;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Interpolator;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int REQUEST_ENABLE_BT = 1;
    private static final int REQUEST_PERMISSION = 2;
    private BluetoothAdapter bluetoothAdapter;
    private ArrayList<BluetoothDevice> deviceList = new ArrayList<>();
    private ArrayAdapter<String> adapter;
    private Handler handler = new Handler(Looper.getMainLooper());
    private static final int STORAGE_PERMISSION_CODE = 1001;
    private boolean isReceiverRegistered = false;
    private LinearLayout choose_device;
    private LinearLayout saerch_device;
    private Button oneDeviceBtn;
    private Button twoDeviceBtn;
    private Integer conDeviceNum=0;
    private BluetoothService bluetoothService;
    private boolean isServiceBound = false;
    private boolean isSelectedLeft=false;
    private boolean isSelectedRight=false;
    private boolean isConnectLeft=false;
    private boolean isConnectRight=false;
    private String macAddressLeft;
    private String macAddressRight;
    private TextView connectDevicetextView;
    private Button backButton;
    private Button leftButton;
    private Button rightButton;
    private String selectDeviceMac;
    private AlertDialog myDialog;
    private static final int CONNECT_TIMEOUT = 2000;
    private Runnable connectTimeoutRunnable;
    private Intent serviceIntent;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isServiceBound = true;
            // 可以进行一些初始化操作，例如设置UI状态
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isServiceBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CrashHandler.getInstance().init(this);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false); // 隐藏默认标题
        choose_device=findViewById(R.id.choose_devices);
        saerch_device=findViewById(R.id.search_devices);
        saerch_device.setVisibility(View.GONE);
        oneDeviceBtn=findViewById(R.id.one_device_btn);
        twoDeviceBtn=findViewById(R.id.double_device_btn);
        connectDevicetextView=findViewById(R.id.connect_device_text);
        backButton=findViewById(R.id.back_device_btn);
        connectDevicetextView.setVisibility(View.GONE);
        checkPermissionsAndStartDiscovery();

        ListView listView = findViewById(R.id.device_list_view);
        Button scanButton = findViewById(R.id.add_device_btn);
        initFileCreate();

//        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
//        if (!dir.exists()) {
//            boolean created = dir.mkdirs(); // 尝试创建目录
//            if (!created) {
//                Log.e("FileTest", "无法创建 Documents 目录");
//            }
//        }
//
//        File magFile = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_DOCUMENTS), "mag1.txt");
//        File accFile = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_DOCUMENTS), "AccGyro1.txt");
//        File matFile = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_DOCUMENTS), "modelPara.mat");
//        utils.copyAssetToFile(this, "modelPara.mat", matFile);
//
//        File zcmatFile = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_DOCUMENTS), "zcmodelPara.mat");
//        utils.copyAssetToFile(this, "zcmodelPara.mat", zcmatFile);
//
//
//        if(!magFile.exists()){
//            Log.d(TAG, "onCreate: magFile" + magFile.getAbsolutePath());
//            utils.copyAssetToFile(this, "mag1.txt", magFile);
//        }
//        else{
//            Log.d(TAG, "NoooooooooCreate: ");
//        }
//
//        if(!accFile.exists()){
//            Log.d(TAG, "onCreate: magFile" + magFile.getAbsolutePath());
//            utils.copyAssetToFile(this, "AccGyro1.txt", accFile);
//        }
//
//        if(!Python.isStarted()){
//            Python.start(new AndroidPlatform(this));
//            System.out.println("Python started");
//        }


        // 获取蓝牙适配器
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 检查蓝牙是否可用
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 注册广播接收器
        registerBleReceiver();

        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Handle the button click event here
                startScanDevice();
            }
        });
        oneDeviceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Handle the button click event here
                isSelectedLeft=false;
                isConnectLeft=false;
                isSelectedRight=false;
                isConnectRight=false;
                conDeviceNum=1;
                choose_device.setVisibility(View.GONE);
                saerch_device.setVisibility(View.VISIBLE);
                connectDevicetextView.setVisibility(View.GONE);
                startDiscovery();
            }
        });
        twoDeviceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Handle the button click event here
                isSelectedLeft=false;
                isConnectLeft=false;
                isSelectedRight=false;
                isConnectRight=false;
                conDeviceNum=2;
                choose_device.setVisibility(View.GONE);
                saerch_device.setVisibility(View.VISIBLE);
                connectDevicetextView.setVisibility(View.VISIBLE);
                connectDevicetextView.setText("左手：未连接   右手：未连接");
                startDiscovery();
            }
        });
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choose_device.setVisibility(View.VISIBLE);
                saerch_device.setVisibility(View.GONE);
                connectDevicetextView.setVisibility(View.GONE);
                isSelectedRight=false;
                isSelectedLeft=false;
                SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.clear();
            }
        });

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
        listView.setAdapter(adapter);

        View customView = LayoutInflater.from(this).inflate(R.layout.dialog_custom, null);
        myDialog = new AlertDialog.Builder(MainActivity.this)
                .setView(customView)
                .create();
        leftButton=customView.findViewById(R.id.leftBtn);
        rightButton=customView.findViewById(R.id.rightBtn);
        leftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                macAddressLeft=selectDeviceMac;
                serviceIntent = new Intent(MainActivity.this, BluetoothService.class);
                serviceIntent.putExtra("DEVICE_ADDRESS_LEFT", macAddressLeft); // 如果需要
                startService(serviceIntent); // 确保服务在后台运行
                bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
                if(conDeviceNum==1) {

                    SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putInt("handDirection", 1);
                    editor.putString("DEVICE_ADDRESS_LEFT", macAddressLeft);
                    editor.apply();
                    myDialog.dismiss();
                }
                if(conDeviceNum==2){
                    isSelectedLeft=true;
                    myDialog.dismiss();
                }
                connectWithTimeout(1);
            }
        });
        rightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                macAddressRight=selectDeviceMac;
                serviceIntent = new Intent(MainActivity.this, BluetoothService.class);
                serviceIntent.putExtra("DEVICE_ADDRESS_RIGHT", macAddressRight); // 如果需要
                startService(serviceIntent); // 确保服务在后台运行
                bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
                if(conDeviceNum==1) {
                    SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putInt("handDirection", 2);
                    editor.putString("DEVICE_ADDRESS_RIGHT", macAddressRight);
                    editor.apply();
                    myDialog.dismiss();
                }
                if(conDeviceNum==2){
                    isSelectedRight=true;
                    myDialog.dismiss();
                }
                connectWithTimeout(2);
            }
        });



        // 设置列表项点击监听器，用于连接设备
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = deviceList.get(position);
                if(conDeviceNum==1) {
                    SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.clear(); // 清空所有数据
                    editor.putInt("conDeviceNum",1);
                    editor.apply();
                    selectDeviceMac=device.getAddress();
                    myDialog.show();
                } else if (conDeviceNum==2) {
                    SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.clear(); // 清空所有数据
                    editor.putInt("conDeviceNum",2);
                    editor.apply();
                    selectDeviceMac=device.getAddress();
                    myDialog.show();
                }
            }
        });


        startScanDevice();
    }
    public void connectWithTimeout(Integer dei) {

        connectTimeoutRunnable = () -> {
            Log.e("BLE", "连接超时！");
            if(dei==1 && isConnectLeft==false){
                Toast.makeText(MainActivity.this,"连接失败，请检查设备或重启设备",Toast.LENGTH_SHORT).show();
                stopService(serviceIntent);
            }
            if (dei==2 && isConnectRight==false) {
                Toast.makeText(MainActivity.this,"连接失败，请检查设备或重启设备",Toast.LENGTH_SHORT).show();
                stopService(serviceIntent);
            }
        };

        handler.postDelayed(connectTimeoutRunnable, CONNECT_TIMEOUT);
    }
    private void initFileCreate(){
        System.out.println("initFileCreate---------");
        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
        if (!dir.exists()) {
            boolean created = dir.mkdirs(); // 尝试创建目录
            if (!created) {
                Log.e("FileTest", "无法创建 Documents 目录");
            }
        }

        File magFile = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), "mag1.txt");
        File accFile = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), "AccGyro1.txt");
        File matFile = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), "modelPara.mat");
        utils.copyAssetToFile(this, "modelPara.mat", matFile);

        File zcmatFile = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), "zcmodelPara.mat");
        utils.copyAssetToFile(this, "zcmodelPara.mat", zcmatFile);


        if(!magFile.exists()){
            Log.d(TAG, "onCreate: magFile" + magFile.getAbsolutePath());
            utils.copyAssetToFile(this, "mag1.txt", magFile);
        }
        else{
            Log.d(TAG, "NoooooooooCreate: ");
        }

        if(!accFile.exists()){
            Log.d(TAG, "onCreate: magFile" + magFile.getAbsolutePath());
            utils.copyAssetToFile(this, "AccGyro1.txt", accFile);
        }

        if(!Python.isStarted()){
            Python.start(new AndroidPlatform(this));
            System.out.println("Python started");
        }

    }
    private void registerBleReceiver() {
        if (!isReceiverRegistered) {
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            filter.addAction(BluetoothDevice.ACTION_FOUND);
            filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
            registerReceiver(receiver, filter);
            isReceiverRegistered = true;
        }
    }

    private void unregisterBleReceiver() {
        if (isReceiverRegistered) {
            unregisterReceiver(receiver);
            isReceiverRegistered = false;
        }
    }
    // 检查权限
    private boolean checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }
        return true;
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        System.out.println("main------requestCode[0]:" + requestCode);

        for(int i=0;i<grantResults.length;i++) {
            System.out.println("main------grantResults[0]:" + grantResults[i]);
        }
        for(int i=0;i<permissions.length;i++) {
            System.out.println("main------permissions[0]:" + permissions[i]);
        }
        initFileCreate();
        if (requestCode == STORAGE_PERMISSION_CODE) {
           for(int i=0;i<permissions.length;i++){
               if(permissions[i]=="android.permission.WRITE_EXTERNAL_STORAGE"){
                    if(grantResults[i]==-1){
                        Toast.makeText(MainActivity.this,"存储文件权限未获取",Toast.LENGTH_SHORT).show();
                    }
               }
           }
        }
    }
    private void startScanDevice() {
        // Handle the button click event here
        Toast.makeText(this, "正在扫描蓝牙设备", Toast.LENGTH_SHORT).show();
        if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        startDiscovery();
        // Add your scanning logic here
    }
    private void checkPermissionsAndStartDiscovery() {
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            permissions = new String[]{
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_CONNECT,
                    Manifest.permission.BLUETOOTH_ADVERTISE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };
        } else {
            permissions = new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.BLUETOOTH,
                    Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };
        }
        List<String> permissionsToRequest = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(permission);
            }
        }
        if (!permissionsToRequest.isEmpty()) {
            ActivityCompat.requestPermissions(this,
                    permissionsToRequest.toArray(new String[0]),
                    REQUEST_PERMISSION);
        }
//        else {
//            startDiscovery();
//        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+
            if (!Environment.isExternalStorageManager()) {
                try {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                } catch (Exception e) {
                    // 某些机型可能没有这个设置项，退回通用页面
                    Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                    startActivity(intent);
                }
            }
        }
        //else {
            // Android 10 及以下
//            int ss = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
//            System.out.println("checkSelfPermission---------ss--------"+ss);
//
//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                    != PackageManager.PERMISSION_GRANTED) {
//                System.out.println("checkSelfPermission-----------------");
//                ActivityCompat.requestPermissions(this,
//                        new String[]{
//                                Manifest.permission.READ_EXTERNAL_STORAGE,
//                                Manifest.permission.WRITE_EXTERNAL_STORAGE
//                        }, 100);
//            } else {
//                Toast.makeText(this, "外部存储权限已授予", Toast.LENGTH_SHORT).show();
//            }
      //  }
//        if (!Environment.isExternalStorageManager()) {
//            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
//            intent.setData(Uri.parse("package:" + getPackageName()));
//            startActivity(intent);
//        }



    }
    private void startDiscovery() {
         bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (bluetoothAdapter == null) {
            Log.e("Bluetooth", "设备不支持蓝牙");
            return;
        }
        registerBleReceiver();

        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            return;
        }
// 清空旧数据
        deviceList.clear();
        if(adapter!=null){
            adapter.clear();
            adapter.notifyDataSetChanged();
        }
        boolean started = bluetoothAdapter.startDiscovery();
        Log.d("Bluetooth", "startDiscovery: " + started);
    }
//    private void startDiscovery() {
//        if (!bluetoothAdapter.isEnabled()) {
//            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
//        } else {
//            // 清空旧数据
//            deviceList.clear();
//            adapter.clear();
//            adapter.notifyDataSetChanged();
//
//            // 启动扫描
//            statusTextView.setText("正在扫描...");
//            bluetoothAdapter.startDiscovery();
//        }
//    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            System.out.println("BroadcastReceiver:"+action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device != null ) {
                    // 获取设备名称和 MAC 地址
                    String deviceName = device.getName();
                    Log.d(TAG, "deviceName：" + deviceName);
                    if (deviceName!="" && deviceName!=null) {
                        if(deviceName.contains("service")) {
                            String deviceHardwareAddress = device.getAddress();
                            String info = (deviceName != null ? deviceName : "未知设备") + " (" + deviceHardwareAddress + ")";
                            Log.d(TAG, "找到设备：" + info);
                            // 检查设备是否已存在于列表中，避免重复添加
                            boolean isDeviceAlreadyAdded = false;
                            for (BluetoothDevice d : deviceList) {
                                if (d.getAddress().equals(device.getAddress())) {
                                    isDeviceAlreadyAdded = true;
                                    break;
                                }
                            }
                            if (!isDeviceAlreadyAdded) {
                                deviceList.add(device);
                                adapter.add(info);
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }
                }
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_OK) {
                startDiscovery();
            } else {
                Toast.makeText(this, "蓝牙未开启，无法扫描", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothService.ACTION_CONNECTEDLEFT);
        filter.addAction(BluetoothService.ACTION_CONNECTEDRIGHT);
        filter.addAction(BluetoothService.ACTION_DISCONNECTEDLEFT);
        filter.addAction(BluetoothService.ACTION_DISCONNECTEDRIGHT);
        filter.addAction(BluetoothService.ACTION_DATA_AVAILABLE);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(bleReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
    }
    private final BroadcastReceiver bleReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothService.ACTION_CONNECTEDLEFT.equals(action)) {
                isConnectLeft=true;
                Toast.makeText(context, "蓝牙已连接", Toast.LENGTH_SHORT).show();
                if (conDeviceNum == 1) {
                        Intent intentLEFT = new Intent(MainActivity.this, BindActivity.class);
                        intentLEFT.putExtra("DEVICE_ADDRESS_LEFT", macAddressLeft);
                        startActivity(intentLEFT);
                }
                if (conDeviceNum == 2) {
                    System.out.println("mainActivity---macAddressLeft:" + macAddressLeft);
                    System.out.println("mainActivity---macAddressRight:" + macAddressRight);
                    if (isConnectLeft ==true && isConnectRight == false) {
                        connectDevicetextView.setText("左手：已连接   右手：未连接");
                    }
                    if (isConnectLeft ==false && isConnectRight == true) {
                        connectDevicetextView.setText("左手：未连接   右手：已连接");
                    }
                    if ((isConnectLeft ==true && isConnectRight == false) || (isConnectLeft ==false && isConnectRight == true)) {
                        Toast.makeText(context, "请选择另一只手的设备进行连接", Toast.LENGTH_SHORT).show();
                    }
                    if (isConnectLeft ==true && isConnectRight ==true) {
                        connectDevicetextView.setText("左手：已连接   右手：已连接");
//                        if (isSelectedRight == true && isSelectedLeft == true) {
                            SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                            SharedPreferences.Editor editor = sp.edit();
                            editor.putString("DEVICE_ADDRESS_LEFT", macAddressLeft);
                            editor.putString("DEVICE_ADDRESS_RIGHT", macAddressRight);
                            editor.apply();
                            Intent intentw = new Intent(MainActivity.this, BindActivity.class);
                            intentw.putExtra("DEVICE_ADDRESS_LEFT", macAddressLeft);
                            intentw.putExtra("DEVICE_ADDRESS_RIGHT", macAddressRight);
                            startActivity(intentw);
//                        }
                    }
                }
            }
            if (BluetoothService.ACTION_CONNECTEDRIGHT.equals(action)) {
                isConnectRight=true;
                Toast.makeText(context, "蓝牙已连接", Toast.LENGTH_SHORT).show();
                if (conDeviceNum == 1) {
                        Intent intentright = new Intent(MainActivity.this, BindActivity.class);
                        intentright.putExtra("DEVICE_ADDRESS_RIGHT", macAddressRight);
                        startActivity(intentright);
                }
                if (conDeviceNum == 2) {
                    System.out.println("mainActivity---macAddressLeft:" + macAddressLeft);
                    System.out.println("mainActivity---macAddressRight:" + macAddressRight);
                    if (isConnectLeft ==true && isConnectRight == false) {
                        connectDevicetextView.setText("左手：已连接   右手：未连接");
                    }
                    if (isConnectLeft ==false && isConnectRight == true) {
                        connectDevicetextView.setText("左手：未连接   右手：已连接");
                    }
                    if ((isConnectLeft ==true && isConnectRight == false) || (isConnectLeft ==false && isConnectRight == true)) {
                        Toast.makeText(context, "请选择另一只手的设备进行连接", Toast.LENGTH_SHORT).show();
                    }
                    if (isConnectLeft ==true && isConnectRight ==true) {
                        connectDevicetextView.setText("左手：已连接   右手：已连接");
//                        if (isSelectedRight == true && isSelectedLeft == true) {
                            SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                            SharedPreferences.Editor editor = sp.edit();
                            editor.putString("DEVICE_ADDRESS_LEFT", macAddressLeft);
                            editor.putString("DEVICE_ADDRESS_RIGHT", macAddressRight);
                            editor.apply();
                            Intent intentw = new Intent(MainActivity.this, BindActivity.class);
                            intentw.putExtra("DEVICE_ADDRESS_LEFT", macAddressLeft);
                            intentw.putExtra("DEVICE_ADDRESS_RIGHT", macAddressRight);
                            startActivity(intentw);
//                        }
                    }
                }
            }
            if (BluetoothService.ACTION_DISCONNECTEDLEFT.equals(action)) {
                isConnectLeft=false;
                Toast.makeText(context, "蓝牙已断开,请重启设备再重新连接", Toast.LENGTH_SHORT).show();
                if(isConnectRight==false) {
                    connectDevicetextView.setText("左手：未连接   右手：未连接");
                }else{
                    connectDevicetextView.setText("左手：未连接   右手：已连接");

                }
            }
            if (BluetoothService.ACTION_DISCONNECTEDRIGHT.equals(action)) {
                isConnectRight=false;
                Toast.makeText(context, "蓝牙已断开,请重启设备再重新连接", Toast.LENGTH_SHORT).show();
                if(isConnectLeft==false) {
                    connectDevicetextView.setText("左手：未连接   右手：未连接");
                }else{
                    connectDevicetextView.setText("左手：已连接   右手：未连接");

                }
            }
            if (BluetoothService.ACTION_DATA_AVAILABLE.equals(action)) {
                Toast.makeText(context, "蓝牙收到数据", Toast.LENGTH_SHORT).show();
            }

        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        // 取消注册广播接收器
      unregisterBleReceiver();
      // 如果扫描正在进行，停止它
        deviceList.clear();
        if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消注册广播接收器
        unregisterBleReceiver();
        deviceList.clear();
        // 如果扫描正在进行，停止它
        if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }

    }
}
